//
//  SelectCountryVC.swift
//  ImGuider X
//
//  Created by 陆涛 on 2018/9/28.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit

class SelectCountryVC: BaseVC {

    @IBOutlet weak var tableview: UITableView!
    
    private let viewmodel = SelectCountryViewModel()
    
    var complete:((Country?)->Void)?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        setupData()
    }
    
    private func setupUI() {
        
        tableview.rowHeight = 44
        self.title = LocalizedString("country_city")
    }
    
    private func setupData() {
        
        viewmodel.reloadData()
        
        viewmodel.loadFinished = {
            
            [weak self] errmsg in
            guard let `self` = self else { return }

            self.tableview.reloadData()
        }
    }
}

extension SelectCountryVC: UITableViewDataSource, UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return viewmodel.indexArray.count;
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        let array = viewmodel.dataSource[viewmodel.indexArray[section]]
        
        return array?.count ?? 0;
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let country = viewmodel.dataSource[viewmodel.indexArray[indexPath.section]]?[indexPath.row]
        
        var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        
        if cell == nil  {
            
            cell = UITableViewCell(style: .value1, reuseIdentifier: "cell")
            cell?.textLabel?.font = kFont14
            cell?.textLabel?.textColor = UIColor.black
            
            cell?.detailTextLabel?.font = kFont12
            cell?.detailTextLabel?.textColor = UIColor.black.withAlphaComponent(0.5)
        }
        
        cell!.textLabel?.text = country?.smartName
        cell!.detailTextLabel?.text = country?.code
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        
        return viewmodel.indexArray[section]
    }
    
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        
        return viewmodel.indexArray
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let country = viewmodel.dataSource[viewmodel.indexArray[indexPath.section]]?[indexPath.row]
        
        self.complete?(country)
        self.navigationController?.popViewController(animated: true)
    }
    
}
